let { User, Option, Question, UserParticipation, OptionScore } = require('../models');
const auth = require('../utils/auth');
// 显示首页
let index_fn = async (ctx, next) => {
    let username = ctx.session.userName;

    let qt = await Question.findAll()

    let qtArr = JSON.parse(JSON.stringify(qt))

    let QtList = []
    qtArr.forEach(item => {
        QtList.push({
            id: item.id,
            name: item.questionName
        })
    })
    console.log(QtList);


    ctx.render('index.html', {
        username,
        QtList
    });
};


//显示添加问卷
let addquestion_fn = async (ctx, next) => {
    ctx.render('addquestion.html')
}
//显示预览问卷
let priviewquestion_fn = async (ctx, next) => {
    let id = ctx.request.query.id;

    let qt = await Question.findOne({ where: { id } })

    let op = await Option.findAll({ where: { questionId: id } })

    let opArr = JSON.parse(JSON.stringify(op))

    let ops = []
    opArr.forEach(item => {
        ops.push({
            id: item.id,
            name: item.optionName
        })
    })

    let obj = {
        name: qt.getDataValue('questionName'),
        remark: qt.getDataValue('remarks'),
        optionList: ops
    }
    ctx.render('priviewquestion.html', obj)
}

//问卷页面
let qestion_fn = async(ctx,next) => {
    let id = ctx.request.query.id;


    if (!ctx.session.userName){
        ctx.session.qtId = id;
        return ctx.redirect('/login')
    } 
   

    let qt = await Question.findOne({ where: { id } })

    let op = await Option.findAll({ where: { questionId: id } })

    let opArr = JSON.parse(JSON.stringify(op))

    let ops = []
    opArr.forEach(item => {
        
        ops.push({
            id: item.id,
            name: item.optionName
        })
    })

    let obj = {
        id,
        name: qt.getDataValue('questionName'),
        remark: qt.getDataValue('remarks'),
        optionList: ops
    }
    ctx.render('share.html', obj)
}

//填写问卷
let fillscore_fn = async (ctx,next) => {
    let obj = ctx.request.body


    let up = await UserParticipation.create({
        userId: ctx.session.userId,
        questionId: obj.id
    })


    let resultArr = []
    for (const key in obj) {
        if (key != 'id') {
            let result = {
                userParticipationId: up.getDataValue('id'),
                optionId: key.substring(5),
                score: obj[key]
            }
            resultArr.push(result)
        }
    }
    console.log(resultArr);
    await OptionScore.bulkCreate(resultArr)

    ctx.body = { code: 200, msg: 'ok' }
}

// 显示登录界面
let login_fn = async (ctx, next) => {
    ctx.render('login.html');
};
// 显示注册界面
let register_fn = async (ctx, next) => {
    ctx.render('register.html', { msg: '' });
};



// 处理登录请求
let loginDone_fn = async (ctx, next) => {
    // 获取从前端传来的数据（用户信息）
    let uid = ctx.request.body.username.trim() || '';
    let pwd = ctx.request.body.password.trim() || '';

    let res = {};

    if (uid.length > 0 && pwd.length > 0) {
        let row = await User.findOne({
            where: {
                username: uid,
                password: pwd
            }
        });
        let u2Json = JSON.stringify(row);
        if (u2Json !== 'null') {
            ctx.session.userId = row.id;
            ctx.session.userName = row.username;
            console.log('登录成功',ctx.session.qtId);
            res = { code: 200, msg: '登录成功', user: uid, id: ctx.session.qtId };
        } else {
            res = { code: 1000, msg: '用户名或密码错误，请确认后重试' };
        }

    } else {
        res = { code: 1000, msg: '用户名和密码不能为空' };
    }

    ctx.body=res
    
};
// 处理注册请求
let registerDone_fn = async (ctx, next) => {
    // 获取从前端传来的数据（用户信息）
    let uid = ctx.request.body.username.trim() || '';
    let pwd = ctx.request.body.password.trim() || '';
    let confirmpwd = ctx.request.body.confirmpassword.trim() || '';

    let res = '';

    // 判断用户名、密码是否为空，为空则返回提示信息；不为空则尝试从数据库中查询是否有同名用户，如果没有，则创建用户；如果有，则返回提示信息；
    // 初步尝试then的玩法，出现了一些顺序问题（前端获取的返回数据为空的情况）
    if (uid.length > 0 && pwd.length > 0 && pwd === confirmpwd) {
        let row = await User.findOne({
            where: {
                username: uid
            }
        });
        let u2Json = JSON.stringify(row);
        if (u2Json === 'null') {
            let u1 = await User.create({
                username: uid,
                password: pwd
            });
            let u1Json = JSON.stringify(u1);
            if (u1Json !== 'null') {
                res = { code: 200, msg: '用户注册成功' };
            } else {
                res = { code: 1000, msg: '因为服务器或者网络原因，用户未注册成功' };
            }
        } else {
            res = { code: 1000, msg: '当前用户名已经注册，请确认后重试' };
        }
    } else {
        res = { code: 1000, msg: '用户名和密码不能为空，且两密码应该一致' };
    }
    // 返回消息
    ctx.body = JSON.stringify(res);
};
// 注销
let logout_fn = async (ctx, next) => {
    ctx.session = null;
    ctx.body = { code: 200, msg: '注销成功' };
}

//创建问卷
let requirequestion_fn = async ctx => {
    let obj = ctx.request.body
    console.log('这是',obj.option);

    if(obj.theme.trim().length===0 || !obj.option){
        return ctx.body={code:333,msg:'错误'}
    }
    console.log('没有错误');

    let qt = await Question.create({
        questionName: obj.theme,
        remarks: obj.remarks
    })

    let opArr = []
    let err=0
    obj.option.forEach(item => {
        if(item.trim().length===0){
            err++;
        }
        opArr.push({
            optionName: item,
            questionId: qt.getDataValue('id')
        })
    })
    
    if(err>0){
        return ctx.body={code:222,msg:'错误'}
    }

    console.log(opArr);

    await Option.bulkCreate(opArr)

    ctx.body = { code: 200, msg: 'ok' }
}

module.exports = {
    '/': ['get', auth, index_fn],
    '/login': ['get', auth, login_fn],
    '/logout': ['post', auth, logout_fn],
    '/register': ['get', register_fn],
    '/loginDone': ['post', loginDone_fn],
    '/registerDone': ['post', registerDone_fn],
    '/addquestion': ['get', addquestion_fn],
    '/priviewquestion': ['get', priviewquestion_fn],
    '/requirequestion': ['post', requirequestion_fn],
    '/fillscore': ['post', fillscore_fn],
    '/qestion': ['get', qestion_fn],
}